/*
 * Copyright (c) 2011, Yawning <yawninglol at gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   * Neither the name of the Mew Developers nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

package yawning.mew.util;

import java.io.FileInputStream;
import java.net.URI;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class BattleNetAuth {
	private BattleNetAuth() {
		try {
			mMac = Mac.getInstance("HmacSHA1");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

		mDateFormat = new SimpleDateFormat("EEEEEEEEE, dd-MMM-yy HH:mm:ss z", Locale.US);
		mDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	private static BattleNetAuth mInstance;

	private boolean mHasKeys = false;
	private SecretKey mPrivateKey;
	private String mPublicKey;
	private DateFormat mDateFormat;
	private Mac mMac;

	private static final String KEY_STORE = "resources/BattleNetAuth.properties";

	public static BattleNetAuth getInstance() {
		if (mInstance == null)
			mInstance = new BattleNetAuth();

		return mInstance;
	}

	public boolean hasKeys() {
		return mHasKeys;
	}

	public boolean loadDefaultKeys() {
		Properties props = new Properties();

		mHasKeys = false;
		mPublicKey = null;
		mPrivateKey = null;

		try {
			props.load(new FileInputStream(KEY_STORE));
		} catch (Exception e) {
			// Fail silently.
			return false;
		}

		String privateKey = props.getProperty("PrivateKey");
		mPublicKey = props.getProperty("PublicKey");

		if (privateKey != null && mPublicKey != null) {
			byte privateKeyBytes[] = privateKey.getBytes();
			mPrivateKey = new SecretKeySpec(privateKeyBytes, "HmacSHA1");
			mHasKeys = true;
		}

		return mHasKeys;
	}

	public boolean setKeys(String publicKey, String privateKey) {
		mPublicKey = publicKey;
		byte privateKeyBytes[] = privateKey.getBytes();
		mPrivateKey = new SecretKeySpec(privateKeyBytes, "HmacSHA1");

		mHasKeys = true;

		return mHasKeys;
	}

	public Map<String,String> buildAuthRequestProps(URI uri) {
		if (!mHasKeys) return null;

		String urlPath = uri.getRawPath();

		// Date is time in GMT, expressed as any one of the formats acceptable in a HTTP header.
		Date date = new Date();		// Note this request should be used sooner rather than later or it will time out.
		String dateStr = mDateFormat.format(date);
		String stringToSign = "GET\n" + dateStr + "\n" + urlPath + "\n";

		try {
			mMac.init(mPrivateKey);
		} catch (InvalidKeyException e) {
			mHasKeys = false;
			return null;
		}

		byte[] digest = mMac.doFinal(stringToSign.getBytes());
		String signature = Base64.encodeBytes(digest);

		Map<String,String> reqProps = new HashMap<String,String>();
		reqProps.put("Accept", "");
		reqProps.put("Date", dateStr);
		reqProps.put("Authorization", "BNET " + mPublicKey + ":" + signature);

		return reqProps;
	}

	public static void main(String args[]) {
		BattleNetAuth auth = BattleNetAuth.getInstance();
		auth.loadDefaultKeys();

		try {
			URI uri = new URI("http", null, "us.battle.net", 80, "/api/wow/realm/status/", null, null);
			Map<String,String> reqProps = auth.buildAuthRequestProps(uri);

			System.out.println(URLFetcher.getInstance().fetchAsString(new URL(uri.toASCIIString()), false, reqProps));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
